<template>
  <div class="chart-container">
    <el-card
        v-for="(chart, index) in charts"
        :key="index"
        class="chart-card"
        shadow="hover"
    >
      <div class="chart-header">
        <h3>{{ chart.title }}</h3>
        <el-tag type="info" size="small">
          {{ chart.type === 'pie' ? '单选题' : '多选题' }}
        </el-tag>
      </div>
      <div
          ref="chartEl"
          :style="{ height: chart.type === 'pie' ? '350px' : '300px' }"
          class="chart-wrapper"
      ></div>
      <div class="chart-summary" v-if="chart.summary">
        <p>{{ chart.summary }}</p>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

const props = defineProps({
  survey: {
    type: Object,
    required: true
  }
})

const chartEl = ref<HTMLElement[]>([])
const charts = ref<any[]>([])

const initCharts = () => {
  charts.value = props.survey.questions
      .filter(q => q.type !== 'text')
      .map(question => {
        const results = calculateResults(question)
        const totalResponses = results.reduce((sum, item) => sum + item.value, 0)

        return {
          title: question.title,
          type: question.type === 'radio' ? 'pie' : 'bar',
          data: results,
          summary: totalResponses > 0 ?
              `共 ${totalResponses} 个回答，最多选择: ${getMostSelected(results)}` :
              '暂无回答数据'
        }
      })
}

const calculateResults = (question: any) => {
  const results: Record<string, number> = {}

  if (question.options) {
    question.options.forEach((opt: string) => {
      results[opt] = 0
    })

    props.survey.submissions.forEach(sub => {
      const answer = sub[question.id]
      if (Array.isArray(answer)) {
        answer.forEach((opt: string) => {
          if (results[opt] !== undefined) results[opt]++
        })
      } else if (answer && results[answer] !== undefined) {
        results[answer]++
      }
    })
  }

  return Object.entries(results).map(([name, value]) => ({
    name,
    value
  }))
}

const getMostSelected = (data: any[]) => {
  if (data.length === 0) return ''
  const max = Math.max(...data.map(item => item.value))
  return data.filter(item => item.value === max).map(item => item.name).join(', ')
}

const renderCharts = () => {
  charts.value.forEach((chart, index) => {
    if (!chartEl.value[index]) return

    const chartInstance = echarts.init(chartEl.value[index])

    const option = chart.type === 'pie' ? getPieOption(chart) : getBarOption(chart)

    chartInstance.setOption(option)

    const handleResize = () => chartInstance.resize()
    window.addEventListener('resize', handleResize)

    // 清理事件监听
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      chartInstance.dispose()
    })
  })
}

const getPieOption = (chart: any) => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'center'
  },
  series: [{
    name: chart.title,
    type: 'pie',
    radius: ['40%', '70%'],
    avoidLabelOverlap: false,
    itemStyle: {
      borderRadius: 6,
      borderColor: '#fff',
      borderWidth: 2
    },
    label: {
      show: true,
      formatter: '{b}: {c} ({d}%)'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: '16px',
        fontWeight: 'bold'
      }
    },
    data: chart.data
  }]
})

const getBarOption = (chart: any) => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value} 人'
    }
  },
  yAxis: {
    type: 'category',
    data: chart.data.map(item => item.name)
  },
  series: [{
    name: chart.title,
    type: 'bar',
    data: chart.data,
    itemStyle: {
      color: function(params: any) {
        const colorList = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
        return colorList[params.dataIndex % colorList.length]
      },
      borderRadius: [0, 4, 4, 0]
    },
    label: {
      show: true,
      position: 'right'
    }
  }]
})

onMounted(() => {
  try {
    initCharts()
    renderCharts()
  } catch (error) {
    ElMessage.error('图表初始化失败')
    console.error('图表初始化错误:', error)
  }
})

watch(() => props.survey, () => {
  initCharts()
  setTimeout(renderCharts, 100)
}, { deep: true })
</script>

<style scoped>
.chart-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(450px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.chart-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.chart-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.chart-wrapper {
  width: 100%;
}

.chart-summary {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}
</style>